using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using twistmachinev2.OPCUA;

namespace twistmachinev2.TwistControl
{
    /// <summary>
    /// 支持数据绑定的圆形状态指示控件
    /// 可以直接关联DynamicDataModel中的布尔属性，根据值显示不同颜色
    /// </summary>
    public class DataBindingStatusCircle : Control
    {
        #region 私有字段
        private DynamicDataModel _dataModel;
        private string _propertyName;
        private bool _currentValue = false;
        private bool _isUpdating = false;
        private Timer _updateTimer;
        private Color _trueColor = Color.LimeGreen;
        private Color _falseColor = Color.Red;
        private Color _borderColor = Color.DarkGray;
        private int _borderWidth = 2;
        private bool _showBorder = true;
        private bool _enableGradient = true;
        private string _trueText = string.Empty;
        private string _falseText = string.Empty;
        private Font _textFont;
        private Color _textColor = Color.White;
        #endregion

        #region 公共属性
        /// <summary>
        /// 关联的数据模型
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public DynamicDataModel DataModel
        {
            get { return _dataModel; }
            set
            {
                if (_dataModel != value)
                {
                    // 取消旧模型的事件订阅
                    if (_dataModel != null)
                    {
                        _dataModel.PropertyChanged -= OnDataModelPropertyChanged;
                    }

                    _dataModel = value;

                    // 订阅新模型的事件
                    if (_dataModel != null)
                    {
                        _dataModel.PropertyChanged += OnDataModelPropertyChanged;
                    }

                    // 立即更新显示
                    UpdateDisplay();
                }
            }
        }

        /// <summary>
        /// 关联的属性名称
        /// </summary>
        [Category("Data Binding")]
        [Description("要绑定的数据模型布尔属性名称，点击右侧按钮可从OPC UA节点中选择")]
        [Editor(typeof(PropertyNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
        public string PropertyName
        {
            get { return _propertyName; }
            set
            {
                if (_propertyName != value)
                {
                    _propertyName = value;
                    UpdateDisplay();
                }
            }
        }

        /// <summary>
        /// True状态时的颜色
        /// </summary>
        [Category("Appearance")]
        [Description("当绑定值为True时显示的颜色")]
        [DefaultValue(typeof(Color), "LimeGreen")]
        public Color TrueColor
        {
            get { return _trueColor; }
            set
            {
                if (_trueColor != value)
                {
                    _trueColor = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// False状态时的颜色
        /// </summary>
        [Category("Appearance")]
        [Description("当绑定值为False时显示的颜色")]
        [DefaultValue(typeof(Color), "Red")]
        public Color FalseColor
        {
            get { return _falseColor; }
            set
            {
                if (_falseColor != value)
                {
                    _falseColor = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 边框颜色
        /// </summary>
        [Category("Appearance")]
        [Description("圆形边框的颜色")]
        [DefaultValue(typeof(Color), "DarkGray")]
        public Color BorderColor
        {
            get { return _borderColor; }
            set
            {
                if (_borderColor != value)
                {
                    _borderColor = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 边框宽度
        /// </summary>
        [Category("Appearance")]
        [Description("圆形边框的宽度")]
        [DefaultValue(2)]
        public int BorderWidth
        {
            get { return _borderWidth; }
            set
            {
                if (_borderWidth != value && value >= 0)
                {
                    _borderWidth = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 是否显示边框
        /// </summary>
        [Category("Appearance")]
        [Description("是否显示圆形边框")]
        [DefaultValue(true)]
        public bool ShowBorder
        {
            get { return _showBorder; }
            set
            {
                if (_showBorder != value)
                {
                    _showBorder = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 是否启用渐变效果
        /// </summary>
        [Category("Appearance")]
        [Description("是否启用渐变填充效果")]
        [DefaultValue(true)]
        public bool EnableGradient
        {
            get { return _enableGradient; }
            set
            {
                if (_enableGradient != value)
                {
                    _enableGradient = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// True状态时显示的文本
        /// </summary>
        [Category("Text")]
        [Description("当值为True时在圆形中显示的文本")]
        public string TrueText
        {
            get { return _trueText; }
            set
            {
                if (_trueText != value)
                {
                    _trueText = value ?? string.Empty;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// False状态时显示的文本
        /// </summary>
        [Category("Text")]
        [Description("当值为False时在圆形中显示的文本")]
        public string FalseText
        {
            get { return _falseText; }
            set
            {
                if (_falseText != value)
                {
                    _falseText = value ?? string.Empty;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 文本字体
        /// </summary>
        [Category("Text")]
        [Description("圆形中文本的字体")]
        public override Font Font
        {
            get { return _textFont ?? base.Font; }
            set
            {
                if (_textFont != value)
                {
                    _textFont = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 文本颜色
        /// </summary>
        [Category("Text")]
        [Description("圆形中文本的颜色")]
        [DefaultValue(typeof(Color), "White")]
        public Color TextColor
        {
            get { return _textColor; }
            set
            {
                if (_textColor != value)
                {
                    _textColor = value;
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 是否启用自动更新（定时刷新显示）
        /// </summary>
        [Category("Data Binding")]
        [Description("是否启用控件级定时自动更新显示")]
        [DefaultValue(false)]
        public bool AutoUpdate { get; set; } = false;

        /// <summary>
        /// 自动更新间隔（毫秒）
        /// </summary>
        [Category("Data Binding")]
        [Description("控件级自动更新间隔，单位毫秒")]
        [DefaultValue(1000)]
        public int UpdateInterval { get; set; } = 1000;

        /// <summary>
        /// 当前绑定的布尔值
        /// </summary>
        [Browsable(false)]
        public bool CurrentValue
        {
            get { return _currentValue; }
        }
        #endregion

        #region 构造函数
        public DataBindingStatusCircle()
        {
            // 设置默认属性
            SetStyle(ControlStyles.AllPaintingInWmPaint | 
                     ControlStyles.UserPaint | 
                     ControlStyles.DoubleBuffer | 
                     ControlStyles.ResizeRedraw, true);
            
            Size = new Size(50, 50);
            // 不设置透明背景色，使用父容器背景色
            // BackColor = Color.Transparent; // 这会导致异常
            
            // 初始化更新定时器
            _updateTimer = new Timer();
            _updateTimer.Tick += UpdateTimer_Tick;
        }
        #endregion

        #region 公共方法
        /// <summary>
        /// 手动更新显示
        /// </summary>
        public void RefreshDisplay()
        {
            UpdateDisplay();
        }

        /// <summary>
        /// 设置数据绑定
        /// </summary>
        /// <param name="dataModel">数据模型</param>
        /// <param name="propertyName">属性名称</param>
        public void SetDataBinding(DynamicDataModel dataModel, string propertyName)
        {
            PropertyName = propertyName;
            DataModel = dataModel; // 最后设置，触发更新
        }

        /// <summary>
        /// 启动自动更新
        /// </summary>
        public void StartAutoUpdate()
        {
            if (AutoUpdate && UpdateInterval > 0)
            {
                _updateTimer.Interval = UpdateInterval;
                _updateTimer.Start();
            }
        }

        /// <summary>
        /// 停止自动更新
        /// </summary>
        public void StopAutoUpdate()
        {
            _updateTimer.Stop();
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 更新显示内容
        /// </summary>
        private void UpdateDisplay()
        {
            if (_isUpdating) return;

            try
            {
                _isUpdating = true;

                if (_dataModel == null || string.IsNullOrEmpty(_propertyName))
                {
                    _currentValue = false;
                    Invalidate();
                    return;
                }

                var value = _dataModel.GetValue(_propertyName);
                bool newValue = ConvertToBool(value);
                
                if (_currentValue != newValue)
                {
                    _currentValue = newValue;
                    Invalidate();
                }
            }
            catch (Exception ex)
            {
                // 发生异常时设置为默认值
                _currentValue = false;
                Invalidate();
                System.Diagnostics.Debug.WriteLine($"DataBindingStatusCircle更新显示失败: {ex.Message}");
            }
            finally
            {
                _isUpdating = false;
            }
        }

        /// <summary>
        /// 转换值为布尔类型
        /// </summary>
        private bool ConvertToBool(object value)
        {
            if (value == null) return false;
            
            if (value is bool boolValue)
                return boolValue;
            
            if (value is string stringValue)
            {
                if (bool.TryParse(stringValue, out bool result))
                    return result;
                return !string.IsNullOrEmpty(stringValue) && stringValue.ToLower() != "false" && stringValue != "0";
            }
            
            if (value is int intValue)
                return intValue != 0;
            
            if (value is double doubleValue)
                return Math.Abs(doubleValue) > 0.001;
            
            return false;
        }

        /// <summary>
        /// 数据模型属性变化事件处理
        /// </summary>
        private void OnDataModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            // 只有当变化的属性是我们关注的属性时才更新
            if (e.PropertyName == _propertyName || string.IsNullOrEmpty(e.PropertyName))
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(UpdateDisplay));
                }
                else
                {
                    UpdateDisplay();
                }
            }
        }

        /// <summary>
        /// 自动更新定时器事件
        /// </summary>
        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            UpdateDisplay();
        }
        #endregion

        #region 重写方法
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            
            // 计算圆形区域
            int diameter = Math.Min(Width, Height) - (_showBorder ? _borderWidth * 2 : 0);
            int x = (Width - diameter) / 2;
            int y = (Height - diameter) / 2;
            Rectangle circleRect = new Rectangle(x, y, diameter, diameter);
            
            // 选择填充颜色
            Color fillColor = _currentValue ? _trueColor : _falseColor;
            
            // 绘制圆形
            using (Brush fillBrush = CreateFillBrush(circleRect, fillColor))
            {
                g.FillEllipse(fillBrush, circleRect);
            }
            
            // 绘制边框
            if (_showBorder && _borderWidth > 0)
            {
                using (Pen borderPen = new Pen(_borderColor, _borderWidth))
                {
                    g.DrawEllipse(borderPen, circleRect);
                }
            }
            
            // 绘制文本
            string displayText = _currentValue ? _trueText : _falseText;
            if (!string.IsNullOrEmpty(displayText))
            {
                using (Brush textBrush = new SolidBrush(_textColor))
                {
                    StringFormat sf = new StringFormat()
                    {
                        Alignment = StringAlignment.Center,
                        LineAlignment = StringAlignment.Center
                    };
                    
                    g.DrawString(displayText, Font, textBrush, circleRect, sf);
                }
            }
        }

        /// <summary>
        /// 创建填充画刷
        /// </summary>
        private Brush CreateFillBrush(Rectangle rect, Color baseColor)
        {
            if (_enableGradient && rect.Width > 10 && rect.Height > 10)
            {
                // 创建径向渐变效果
                Color lightColor = ControlPaint.Light(baseColor, 0.3f);
                Color darkColor = ControlPaint.Dark(baseColor, 0.2f);
                
                GraphicsPath path = new GraphicsPath();
                path.AddEllipse(rect);
                
                PathGradientBrush gradientBrush = new PathGradientBrush(path);
                gradientBrush.CenterColor = lightColor;
                gradientBrush.SurroundColors = new Color[] { darkColor };
                gradientBrush.CenterPoint = new PointF(rect.X + rect.Width * 0.3f, rect.Y + rect.Height * 0.3f);
                
                return gradientBrush;
            }
            else
            {
                return new SolidBrush(baseColor);
            }
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            
            // 控件创建后启动自动更新
            if (AutoUpdate)
            {
                StartAutoUpdate();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // 清理资源
                StopAutoUpdate();
                _updateTimer?.Dispose();
                
                if (_dataModel != null)
                {
                    _dataModel.PropertyChanged -= OnDataModelPropertyChanged;
                }
            }
            base.Dispose(disposing);
        }
        #endregion
    }
}